const rewire = require('rewire')
const cache = rewire('../common/cache.cjs')
const utils = rewire('../common/utils.cjs')

function wrapCacheFn(f, key, expired) {
  return async function(...args) {
    const cacheKey = key + JSON.stringify(args)
    let rs = await cache.getCache(cacheKey)
    if (rs || await cache.existsCache(cacheKey)) {
      return rs
    }
    rs = await f(...args)
    await cache.saveCache(cacheKey, rs, expired)
    return rs
  }
}


let lastExeTime = null
function wrapIntervalWaitFn(f, ms) {
  return async function(...args) {
    const now = utils.currentMs()
    if (lastExeTime && (now - lastExeTime) < ms) {
      await utils.sleep(ms - (now - lastExeTime))
    }
    const rs = await f(...args)
    lastExeTime = utils.currentMs()
    return rs
  }
}

module.exports = {wrapCacheFn, wrapIntervalWaitFn}
